<?php
require 'db.php'; // 数据库连接
require 'vendor/autoload.php'; // 引入 Composer 自动加载器
include_once 'secret/jwt.php';

use Firebase\JWT\JWT;

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = $_POST['username'];
    $hashedPassword = $_POST['hashed_password'];

    if (empty($username) || empty($hashedPassword)) {
        echo "<script>
            alert('用户名和密码不能为空');
            window.location.href = 'index.php';
        </script>";
        exit();
    }

    try {
        $stmt = $conn->prepare("SELECT id, username, password, role FROM users WHERE username = ?");
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $result = $stmt->get_result();
        $user = $result->fetch_assoc();
        $stmt->close();

        if ($user && $hashedPassword === $user['password']) {
            $payload = [
                'iss' => 'your_website.com',  // 发行者
                'aud' => 'your_website.com',  // 接收者
                'iat' => time(),              // 颁发时间
                'exp' => time() + 1800,       // 过期时间（30分钟后）
                'data' => [
                    'username' => $user['username'],
                    'role' => $user['role'],
                    'id' => $user['id']
                ]
            ];

            $jwt = JWT::encode($payload, $secretKey, 'HS256');
            setcookie('token', $jwt, time() + 3600, "/");

            header('Location: profile.html');
            exit();
        } else {
            echo "<script>
                alert('用户名或密码不正确');
                window.location.href = 'login_form.html';
            </script>";
        }
    } catch (Exception $e) {
        echo "<script>
            alert('登录失败: " . $e->getMessage() . "');
            window.location.href = 'login_form.html';
        </script>";
    }
}
?>



